package com.dragon.backstage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragon.backstage.convert.UserLoginLogConvert;
import com.dragon.backstage.domain.excel.UserLoginLogExportExcel;
import com.dragon.backstage.domain.param.userLoginLog.UserLoginLogParam;
import com.dragon.backstage.domain.vo.userLoginLog.UserLoginLogVo;
import com.dragon.backstage.service.UserLoginLogService;
import com.dragon.common.domain.vo.PaginationVo;
import com.dragon.common.utils.AjaxResult;
import com.dragon.common.utils.time.LocalDateUtils;
import com.dragon.interfaces.domain.request.userLoginLog.UserLoginLogRequest;
import com.dragon.interfaces.entity.UserLoginLog;
import com.dragon.interfaces.mapper.UserLoginLogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户登陆记录 服务实现类
 * </p>
 *
 * @author dragon
 * @since 2024-08-01 18:08:24
 */
@Service
public class UserLoginLogServiceImpl extends ServiceImpl<UserLoginLogMapper, UserLoginLog> implements UserLoginLogService {

    @Resource
    private UserLoginLogMapper userLoginLogMapper;


    /**
     * 用户登陆日志列表
     *
     * @param userLoginLogParam 查询参数
     * @return 分页数据
     */
    @Override
    public AjaxResult<PaginationVo<UserLoginLogVo>> userLoginLogList(UserLoginLogParam userLoginLogParam) {
        UserLoginLogRequest userLoginLogRequest = UserLoginLogConvert.toUserLoginLogRequest(userLoginLogParam);

        List<UserLoginLog> userLoginLogs = userLoginLogMapper.selectUserLoginLogList(userLoginLogRequest);
        Integer total = userLoginLogMapper.selectUserLoginLogCount(userLoginLogRequest);

        List<UserLoginLogVo> userLoginLogVos = new ArrayList<>(16);
        if (CollectionUtils.isNotEmpty(userLoginLogs)) {
            userLoginLogVos = userLoginLogs.stream().map(UserLoginLogConvert::toUserLoginLogVo).toList();
        }

        return AjaxResult.succeedWith(PaginationVo
            .<UserLoginLogVo>builder()
            .total(total)
            .rows(userLoginLogVos)
            .build()
        );
    }

    /**
     * 删除用户登陆日志
     *
     * @param loginIds 登陆ID集合
     * @return 删除结果
     */
    @Override
    public AjaxResult<Void> deleteUserLoginLog(List<Long> loginIds) {
        if (CollectionUtils.isEmpty(loginIds)) {
            return AjaxResult.failed("登陆ID不能为空");
        }

        Long logNum = userLoginLogMapper.selectCount(new QueryWrapper<UserLoginLog>()
            .in(UserLoginLog.LOGIN_ID, loginIds)
        );
        if (logNum < 1) {
            return AjaxResult.failed("用户登陆日志不存在");
        }

        boolean flag = userLoginLogMapper.deleteByIds(loginIds) > 0;
        if (!flag) {
            return AjaxResult.failed("删除用户登陆日志失败");
        }

        return AjaxResult.succeed();
    }

    /**
     * 导出用户登陆日志
     *
     * @param response          响应
     * @param userLoginLogParam 查询参数
     */
    @Override
    public void exportUserLoginLog(HttpServletResponse response, UserLoginLogParam userLoginLogParam) throws IOException {
        userLoginLogParam.setPageNum(1);
        userLoginLogParam.setPageSize(Integer.MAX_VALUE);

        UserLoginLogRequest userLoginLogRequest = UserLoginLogConvert.toUserLoginLogRequest(userLoginLogParam);

        List<UserLoginLog> userLoginLogs = userLoginLogMapper.selectUserLoginLogList(userLoginLogRequest);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户登陆日志_" + LocalDateUtils.getUnsignedLocalDateTimeStr(), StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<UserLoginLogExportExcel> userOperateLogExportExcels = userLoginLogs.stream().map(UserLoginLogConvert::toUserLoginLogExportExcel).collect(Collectors.toList());

        EasyExcel.write(response.getOutputStream(), UserLoginLogExportExcel.class).sheet("用户登陆日志").doWrite(userOperateLogExportExcels);
    }

    /**
     * 清空用户登陆日志
     *
     * @return 清空结果
     */
    @Override
    public AjaxResult<Void> cleanUserLoginLog() {
        userLoginLogMapper.cleanUserLoginLog();

        return AjaxResult.succeed();
    }

}
